package com.eightbears.beboy.ui.merchant.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.eightbears.beboy.R;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.cache.DistrictCache;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GetCategory;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.InputMethodUtils;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.builder.PostFormBuilder;
import com.eightbears.beboy.base.util.okhttp.callback.FileCallBack;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.dialog.ClassDialog;
import com.eightbears.beboy.base.view.image.adapter.ImagePickerAdapter;
import com.eightbears.beboy.base.view.image.ui.ImageGridActivity;
import com.eightbears.beboy.base.view.image.ui.ImageViewDelActivity;
import com.eightbears.beboy.base.view.image.view.ImageItem;
import com.eightbears.beboy.base.view.image.view.ImagePicker;
import com.eightbears.beboy.base.view.picker.AddressPickTask;
import com.eightbears.beboy.base.view.picker.entity.City;
import com.eightbears.beboy.base.view.picker.entity.County;
import com.eightbears.beboy.base.view.picker.entity.Province;
import com.eightbears.beboy.entity.LocationEntity;
import com.eightbears.beboy.entity.ShopDetailEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.user.activity.SelLocationActivity;
import com.eightbears.greendao.District;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CAHCE_IMAGE_FILE;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER_ACCEPT;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER_ACCEPT_VALUE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_SHOPS_LIST;
import static com.eightbears.beboy.base.util.CommonAPI.URL_SHOP_APPLIACTION;
import static com.eightbears.beboy.ui.user.activity.ShopInfoActivity.PARAMS_SHOP_DETAIL;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_ADDRESS;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_CITY;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_DISTRICT;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_LATITUDE;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_LONGITUDE;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_PROVINCE;

public class ShopApplyActivity extends BaseActivity
        implements ImagePickerAdapter.OnRecyclerViewItemClickListener {

    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    public static final int REQUEST_CODE_LOCATION = 1;
    public static final String EVENT_UPDATE_SHOP = "UpdateShopSuccess";

    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.et_shop_name)
    TextView et_shop_name;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.et_manager_name)
    TextView et_manager_name;
    @BindView(R.id.text_classify)
    TextView text_classify;
    @BindView(R.id.tv_district)
    TextView tv_district;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.et_phone)
    EditText et_phone;
    @BindView(R.id.et_price)
    TextView et_price;
    @BindView(R.id.et_dis)
    EditText et_dis;
    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.iv_manager_class)
    ImageView iv_manager_class;
    @BindView(R.id.iv_shopapply_location)
    ImageView iv_shopapply_location;
    @BindView(R.id.view_loading)
    View view_loading;
    @BindView(R.id.tv_loading_text)
    TextView tv_loading_text;
    @BindView(R.id.ll_manager_name)
    LinearLayout ll_manager_name;

    private ArrayList<ImageItem> selImageList;                  //当前选择的所有图片
    private int maxImgCount = 9;                                //允许选择图片最大数
    private ImagePickerAdapter adapter;
    private String mLatitude = "";
    private String mLongitude = "";
    private String mAddress = "";
    private String provinceId = "";
    private String districtId = "";
    private String cityId = "";


    private String shopName, managerName, classesId, fullCity, phone, price, disContent;
    private String districtName, cityName, provinceName;
    private List<String> images = new ArrayList<>();
    private ShopDetailEntity shopDetailEntity;
    private ClassDialog mClassDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_apply);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        selImageList = new ArrayList<>();
        if (null != getExtras()) {
            shopDetailEntity = (ShopDetailEntity) getExtras().get(PARAMS_SHOP_DETAIL);
            ll_manager_name.setVisibility(View.GONE);
            tv_title.setText(R.string.text_shop_info_update);
            tv_loading_text.setText(R.string.text_loading_data_wait);
            view_loading.setVisibility(View.VISIBLE);
            initShopInfo();
        } else {
            tv_loading_text.setText(R.string.text_applying_wait);
            tv_title.setText(R.string.text_shop_apply);
        }
        initAdapter();
    }

    @Override
    protected void initData() {
        LocationEntity locationEntity = SPUtil.getUserLocation();
        if (null != locationEntity) {
            provinceName = locationEntity.getProvinceName();
            cityName = locationEntity.getCityName();
            districtName = locationEntity.getDistrictName();
        }
    }

    @Override
    protected void initEvent() {
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }


    @OnClick(R.id.rl_classify)
    void selClassify() {
        mClassDialog = new ClassDialog(mContext, R.style.MyDialog);
        mClassDialog.setOnItemClickListener(new ClassDialog.onDialogItemClickListener() {
            @Override
            public void onItemClick(String s, String id) {
                iv_manager_class.setVisibility(View.GONE);
                text_classify.setVisibility(View.VISIBLE);
                text_classify.setText(s);
                classesId = id;
                mClassDialog.dismiss();
            }
        });
        mClassDialog.show();
        mClassDialog.setCancelable(true);//默认是true
        mClassDialog.setCanceledOnTouchOutside(true);//默认是true
    }

    @OnClick(R.id.rl_city)
    void selCity() {
        AddressPickTask task = new AddressPickTask(this);
        task.setHideProvince(false);
        task.setHideCounty(false);
        task.setCallback(new AddressPickTask.Callback() {
            @Override
            public void onAddressPicked(Province province, City city, County county) {
                fullCity = province.getName() + " " + city.getName() + " " + county.getName();
                tv_district.setText(fullCity);
            }

            @Override
            public void onAddressInitFailed() {
                ShowToast.showShortToast(getString(R.string.error_init_data));
            }

        });
        task.execute(provinceName, cityName, districtName);
    }

    @OnClick(R.id.rl_address)
    void selAddress() {
        startActivityForResult(new Intent(mContext, SelLocationActivity.class), REQUEST_CODE_LOCATION);
        overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                //打开选择,本次允许选择的数量
                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                Intent intent = new Intent(this, ImageGridActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SELECT);
                overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(this, ImageViewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                break;
        }
    }

    private int i = 0;
    private void downShopImage() {
        String fileName = System.currentTimeMillis() + "_";
        OkHttpUtils.get().url(images.get(i))
                .build().execute(new FileCallBack(CAHCE_IMAGE_FILE, fileName + i + ".png") {
            @Override
            public void onResponse(File response) {
                i++;
                selImageList.add(new ImageItem(response.getAbsolutePath()));
                if(i < images.size()) {
                    downShopImage();
                } else {
                    view_loading.setVisibility(View.GONE);
                    initAdapter();
                }
            }

            @Override
            public void inProgress(float progress) {

            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
            }

        });

    }

    private void initShopInfo() {
        provinceId = shopDetailEntity.getData().getProvince_id();
        cityId = shopDetailEntity.getData().getCity_id();
        districtId = shopDetailEntity.getData().getDistrict_id();
        District province = DistrictCache.getInstance(this).getCacheById(provinceId);
        District city = DistrictCache.getInstance(this).getCacheById(cityId);
        District district = DistrictCache.getInstance(this).getCacheById(districtId);
        fullCity = province.getName() + " " + city.getName() + " " + district.getName();

        classesId = shopDetailEntity.getData().getType();
        mLongitude = shopDetailEntity.getData().getLongitude();
        mLatitude = shopDetailEntity.getData().getLatitude();
        mAddress = shopDetailEntity.getData().getAddress();

        et_shop_name.setText(shopDetailEntity.getData().getTitle());
        text_classify.setText(GetCategory.getCategoryNameById(shopDetailEntity.getData().getType()));
        tv_district.setText(fullCity);
        tv_address.setText(mAddress);
        et_phone.setText(shopDetailEntity.getData().getPhone());
        et_price.setText(shopDetailEntity.getData().getConsumption());
        et_dis.setText(shopDetailEntity.getData().getContent().getContent());

        images.add(shopDetailEntity.getData().getCover());
        if (shopDetailEntity.getData().getImages() != null) {
            images.addAll(shopDetailEntity.getData().getImages());
        }

        downShopImage();
    }


    /**
     * 初始化适配器
     */
    private void initAdapter() {
        adapter = new ImagePickerAdapter(this, selImageList, maxImgCount);
        adapter.setOnItemClickListener(this);
        rv_list.setLayoutManager(new GridLayoutManager(this, 4));
        rv_list.setHasFixedSize(true);
        rv_list.setAdapter(adapter);
    }


    private boolean checkInput() {

        shopName = et_shop_name.getText().toString().trim();
        managerName = et_manager_name.getText().toString().trim();
        phone = et_phone.getText().toString().trim();
        price = et_price.getText().toString().trim();
        disContent = et_dis.getText().toString().trim();

        if (TextUtils.isEmpty(shopName)) {
            ShowToast.showShortToast(R.string.hint_apply_shop_name);
            return false;
        }

        if (shopDetailEntity == null) {
            if (TextUtils.isEmpty(managerName)) {
                ShowToast.showShortToast(R.string.hind_apply_manager_name);
                return false;
            }
        }

        if (TextUtils.isEmpty(classesId)) {
            ShowToast.showShortToast(R.string.hint_apply_classy);
            return false;
        }

        if (TextUtils.isEmpty(fullCity)) {
            ShowToast.showShortToast(R.string.hint_apply_select_city);
            return false;
        }

        if (TextUtils.isEmpty(mAddress)) {
            ShowToast.showShortToast(R.string.hint_apply_address);
            return false;
        }

        if (TextUtils.isEmpty(phone)) {
            ShowToast.showShortToast(R.string.hint_apply_phony);
            return false;
        }

        if (TextUtils.isEmpty(price)) {
            ShowToast.showShortToast(R.string.hint_apply_price);
            return false;
        }

        if (TextUtils.isEmpty(disContent)) {
            ShowToast.showShortToast(R.string.hint_apply_shop_dis);
            return false;
        }

        return true;
    }

    @OnClick(R.id.btn_submit)
    void btnSubmit() {
        if (checkInput()) {
            tv_loading_text.setText(R.string.text_applying_wait);
            view_loading.setVisibility(View.VISIBLE);
            submitApply();
        }
    }

    private void submitApply() {

        PostFormBuilder builder = OkHttpUtils.post();
        if (shopDetailEntity == null) {
            builder.url(URL_SHOP_APPLIACTION);
            builder.addHeader(KEY_HTTP_HEADER_ACCEPT, KEY_HTTP_HEADER_ACCEPT_VALUE);
            builder.addParams("manager_name", managerName);
        } else {
            builder.url(URL_SHOPS_LIST + shopDetailEntity.getData().getShop_id());
        }
        builder.addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken());
        builder.addParams("title", shopName);
        builder.addParams("type", classesId);
        builder.addParams("consumption", price);
        builder.addParams("content", disContent);
        builder.addParams("phone", phone);
        builder.addParams("province_id", provinceId);
        builder.addParams("city_id", cityId);
        builder.addParams("district_id", districtId);
        builder.addParams("address", mAddress);
        builder.addParams("longitude", mLongitude);
        builder.addParams("latitude", mLatitude);
        if (selImageList.size() > 0) {
            builder.addFile("cover", "cover_" + System.currentTimeMillis(), new File(selImageList.get(0).path));
            if (selImageList.size() == 1) {
                builder.addParams("no_image", "1");
            } else {
                selImageList.remove(0);
                for (ImageItem file : selImageList) {
                    builder.addFile("images[]", "images_" + System.currentTimeMillis(), new File(file.path));//图片
                }
            }
        } else {
            view_loading.setVisibility(View.GONE);
            ShowToast.showShortToast(getString(R.string.text_apply_upload_cover));
            return;
        }
        builder.build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                view_loading.setVisibility(View.GONE);
                ShowToast.showShortToast(getString(R.string.alert_submit_success));
                if(shopDetailEntity != null) {
                    EventBus.getDefault().post(EVENT_UPDATE_SHOP);
                }
                finish();
            }

            @Override
            public void onError(Call call, Exception e) {
                view_loading.setVisibility(View.GONE);
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(ShopApplyActivity.this, status_error);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                selImageList.addAll(images);
                adapter.setImages(selImageList);
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                selImageList.clear();
                selImageList.addAll(images);
                adapter.setImages(selImageList);
            }
        } else if (requestCode == REQUEST_CODE_LOCATION) {
            if (null == data) {
                ShowToast.showLongToast(getString(R.string.text_canceled));
                return;
            }

            mLatitude = String.valueOf(data.getExtras().getDouble(PARAMS_LATITUDE));
            mLongitude = String.valueOf(data.getExtras().getDouble(PARAMS_LONGITUDE));
            mAddress = data.getExtras().getString(PARAMS_ADDRESS);
            provinceId = data.getExtras().getString(PARAMS_PROVINCE);
            districtId = data.getExtras().getString(PARAMS_DISTRICT);
            cityId = data.getExtras().getString(PARAMS_CITY);

            tv_address.setText(mAddress);
            iv_shopapply_location.setVisibility(View.GONE);
        }
    }

    @Override
    public void finish() {
        super.finish();
        InputMethodUtils.closeInputMethod(this, et_shop_name);
    }
}
